package com.foodorder.controller;

import com.foodorder.dto.ApiResponse;
import com.foodorder.entity.Product;
import com.foodorder.service.ProductService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.HashMap;

/**
 * 商品控制器
 */
@RestController
@RequestMapping("/products")
@RequiredArgsConstructor
@CrossOrigin(origins = "*")
public class ProductController {
    
    private final ProductService productService;
    
    /**
     * 根据店铺ID获取商品列表
     */
    @GetMapping("/store/{storeId}")
    public ApiResponse<List<Product>> getProductsByStore(@PathVariable Long storeId) {
        List<Product> products = productService.findByStoreId(storeId);
        return ApiResponse.success(products);
    }
    
    /**
     * 根据店铺ID和分类ID获取商品列表
     */
    @GetMapping("/store/{storeId}/category/{categoryId}")
    public ApiResponse<List<Product>> getProductsByStoreAndCategory(
            @PathVariable Long storeId,
            @PathVariable Long categoryId) {
        List<Product> products = productService.findByStoreIdAndCategoryId(storeId, categoryId);
        return ApiResponse.success(products);
    }
    
    /**
     * 根据店铺ID获取推荐商品
     */
    @GetMapping("/store/{storeId}/recommended")
    public ApiResponse<List<Product>> getRecommendedProducts(@PathVariable Long storeId) {
        List<Product> products = productService.findRecommendedByStoreId(storeId);
        return ApiResponse.success(products);
    }
    
    /**
     * 获取商品详情
     */
    @GetMapping("/{id}")
    public ApiResponse<Product> getProductDetail(@PathVariable Long id) {
        Product product = productService.findById(id);
        if (product == null) {
            return ApiResponse.notFound("商品不存在");
        }
        return ApiResponse.success(product);
    }
    
    /**
     * 管理端分页查询商品
     */
    @GetMapping("/admin")
    public ApiResponse<Map<String, Object>> getProductsForAdmin(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) String category,
            @RequestParam(required = false) String status,
            @RequestParam(required = false) Long storeId) {
        try {
            Pageable pageable = PageRequest.of(page - 1, size);
            Page<Product> productPage = productService.findProductsForAdmin(keyword, category, status, storeId, pageable);
            
            Map<String, Object> result = new HashMap<>();
            result.put("list", productPage.getContent());
            result.put("total", productPage.getTotalElements());
            result.put("page", page);
            result.put("size", size);
            result.put("totalPages", productPage.getTotalPages());
            
            return ApiResponse.success(result);
        } catch (Exception e) {
            return ApiResponse.error("查询商品失败: " + e.getMessage());
        }
    }
    
    /**
     * 搜索商品
     */
    @GetMapping("/search")
    public ApiResponse<Page<Product>> searchProducts(
            @RequestParam String keyword,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "20") int size) {
        try {
            Pageable pageable = PageRequest.of(page, size);
            Page<Product> products = productService.searchProducts(keyword, pageable);
            return ApiResponse.success(products);
        } catch (Exception e) {
            return ApiResponse.error("搜索商品失败: " + e.getMessage());
        }
    }
    
    /**
     * 根据店铺ID按销量排序获取商品
     */
    @GetMapping("/store/{storeId}/by-sales")
    public ApiResponse<List<Product>> getProductsByStoreOrderBySales(@PathVariable Long storeId) {
        List<Product> products = productService.findByStoreIdOrderBySales(storeId);
        return ApiResponse.success(products);
    }
    
    /**
     * 创建商品
     */
    @PostMapping
    public ApiResponse<Product> createProduct(@RequestBody Product product) {
        try {
            Product savedProduct = productService.save(product);
            return ApiResponse.success(savedProduct);
        } catch (Exception e) {
            return ApiResponse.error("创建商品失败: " + e.getMessage());
        }
    }
    
    /**
     * 更新商品
     */
    @PutMapping("/{id}")
    public ApiResponse<Product> updateProduct(@PathVariable Long id, @RequestBody Product product) {
        try {
            Product existingProduct = productService.findById(id);
            if (existingProduct == null) {
                return ApiResponse.error("商品不存在");
            }
            product.setId(id);
            Product savedProduct = productService.save(product);
            return ApiResponse.success(savedProduct);
        } catch (Exception e) {
            return ApiResponse.error("更新商品失败: " + e.getMessage());
        }
    }
    
    /**
     * 删除商品
     */
    @DeleteMapping("/{id}")
    public ApiResponse<Void> deleteProduct(@PathVariable Long id) {
        try {
            Product product = productService.findById(id);
            if (product == null) {
                return ApiResponse.error("商品不存在");
            }
            productService.deleteById(id);
            return ApiResponse.success(null);
        } catch (Exception e) {
            return ApiResponse.error("删除商品失败: " + e.getMessage());
        }
    }
    
    /**
     * 批量删除商品
     */
    @DeleteMapping("/batch")
    public ApiResponse<Void> deleteProducts(@RequestBody List<Long> ids) {
        try {
            productService.deleteByIds(ids);
            return ApiResponse.success(null);
        } catch (Exception e) {
            return ApiResponse.error("批量删除商品失败: " + e.getMessage());
        }
    }
    
    /**
     * 更新商品状态
     */
    @PutMapping("/{id}/status")
    public ApiResponse<Void> updateProductStatus(@PathVariable Long id, @RequestParam String status) {
        try {
            productService.updateStatus(id, status);
            return ApiResponse.success(null);
        } catch (Exception e) {
            return ApiResponse.error("更新商品状态失败: " + e.getMessage());
        }
    }
    
    /**
     * 更新商品库存
     */
    @PutMapping("/{id}/stock")
    public ApiResponse<Void> updateProductStock(@PathVariable Long id, @RequestParam Integer stock) {
        try {
            productService.updateStock(id, stock);
            return ApiResponse.success(null);
        } catch (Exception e) {
            return ApiResponse.error("更新商品库存失败: " + e.getMessage());
        }
    }
} 